﻿using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Web.UI;
using System.Web.UI.WebControls;
using ErikLieben.SharePoint.Generic;
using Microsoft.Office.Server;
using Microsoft.Office.Server.UserProfiles;
using Microsoft.SharePoint;

namespace ErikLieben.SharePoint.WebParts
{
    [Guid("db268198-fcb4-4b55-9100-2854fdd44921")]
    public class FaceBookWebPart : BaseWebPart
    {
        #region [ Constructor ]
        public FaceBookWebPart() { }
        #endregion

        #region [ Fields ]

        private DataList lstEmployeesList;

        #endregion

        #region [ Overrided Methods ]

        protected override string DeterminateView()
        {
            return @"~/_controltemplates/FaceBookWebPart/FaceBookWebPartControl.ascx";
        }

        protected override void WireUpControls()
        {
            if (FindControl<DataList>("lstEmployeesList", out lstEmployeesList, true))
                FillDataListWithUserData(lstEmployeesList);
        }

        protected override void WireUpSharePointControls(Control uiTemplate)
        {

        }

        #endregion

        #region [ Private Methods ]

        private void FillDataListWithUserData(BaseDataList list)
        {
            List<FaceBookUser> users = new List<FaceBookUser>();
            UserProfileManager profileManager = new UserProfileManager(ServerContext.Current);
            foreach (UserProfile profile in profileManager)
            {
                if (Parse<Boolean>(profile["VisibleInFaceBook"]))
                    users.Add(new FaceBookUser()
                    {
                        Name = Parse<String>(profile["PreferredName"]),
                        Photo = Parse<String>(profile["PictureURL"]),
                        AboutMe = Parse<String>(profile["AboutMe"]),
                        Title = Parse<String>(profile["Title"]),
                        MySiteUrl = Parse<String>(profile["PersonalSpace"]),
                        HireDate = Parse<DateTime>(profile["SPS-HireDate"]),
                        Department = Parse<String>(profile["Department"])
                    });
            }

            lstEmployeesList.DataSource = users;
            lstEmployeesList.DataBind();
        }

        private static T Parse<T>(UserProfileValueCollection valueCollection) where T : IConvertible
        {
            if (valueCollection == null || valueCollection.Value == null) return default(T);

            try
            {
                return (T)Convert.ChangeType(valueCollection.Value, typeof(T));
            }
            catch (Exception) { }

            return default(T);
        }
        #endregion
    }
}
